<?php

namespace App\Models;


use App\Models\Traits\ScopeTrait;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class Car extends Model
{
    use ScopeTrait;

    const REFUND_STATUS_NORMAL = 1;
    const REFUND_STATUS_OFF = 0;

    public static $statusMap = [
        self::REFUND_STATUS_NORMAL => '正常',
        self::REFUND_STATUS_OFF    => '已下架',
    ];

    protected $appends = ['new_price_del', 'new_mileage'];

    protected $fillable = [
        'brand', 'series', 'frame_no', 'new_price', 'real_price', 'mileage',
        'first_at', 'filed_at', 'diagnosis_at', 'engineer', 'engineer_comment',
        'diagnosis_report', 'appraisal_report', 'status', 'created_at', 'updated_at'
    ];

    // 鉴定报告是要付费的，只能在可见的情况下使用
    protected $hidden = ['appraisal_report'];

    // 定义新车价格
    public function getNewPriceDelAttribute()
    {
        return $this->new_price . ' 万';
    }

    // 定义实际售价
    public function getNewMileageAttribute($value)
    {
        return floor($value / 100) / 100 . ' 公里';
    }

    // 获取诊断报告图片
    public function getDiagnosisReportAttribute($value)
    {
        $value = explode(',', $value);
        $attachment_info = Attachment::whereIn('id', $value)->get()->toArray();
        $data = [];
        if ($attachment_info) {
            foreach ($attachment_info as $key => $value) {
                $data[$key]['attachment_id'] = $value['id'];
                $data[$key]['url'] = $value['domain'] . '/' . $value['link_path'] . '/' . $value['storage_name'];
            }
        }
        return $data;
    }

//    // 获取鉴定报告图片
    public function getAppraisalReportAttribute($value)
    {
        $value = explode(',', $value);
        $attachment_info = Attachment::whereIn('id', $value)->get()->toArray();
        $data = [];
        if ($attachment_info) {
            foreach ($attachment_info as $key => $value) {
                $data[$key]['attachment_id'] = $value['id'];
                $data[$key]['url'] = $value['domain'] . '/' . $value['link_path'] . '/' . $value['storage_name'];
            }
        }
        return $data;
    }

    public function saveAction($input)
    {
        try {
            if ($input['diagnosis_report'] || $input['appraisal_report']) {
                // 把有效的attachment_id对应的 use_status= F 变成 T
                $attachment_id = array_merge($input['diagnosis_report'], $input['appraisal_report']);
                $this->saveAttachmentAfterSave($attachment_id);
            }
            $input['diagnosis_report'] = implode(',', $input['diagnosis_report']);
            $input['appraisal_report'] = implode(',', $input['appraisal_report']);
            $this->fill($input);
            $this->save();
            return $this->baseSucceed([], '操作成功');
        } catch (\Exception $e) {
            throw $e;
            return $this->baseFailed('内部错误');
        }
    }

    public function updateAction($input)
    {
        // 旧的图
        $old_diagnosis_report = $this->diagnosis_report;
        $old_appraisal_report = $this->appraisal_report;
        $old_diagnosis_id = [];
        $old_appraisal_id = [];
        if ($old_diagnosis_report) {
            foreach ($old_diagnosis_report as $key => $value) {
                $old_diagnosis_id[$key] = $value['attachment_id'];
            }
        }
        if ($old_appraisal_report) {
            foreach ($old_appraisal_report as $key => $value) {
                $old_appraisal_id[$key] = $value['attachment_id'];
            }
        }
        $old_image = array_merge($old_diagnosis_id, $old_appraisal_id);
        // 新的图
        if ($input['diagnosis_report'] || $input['appraisal_report']) {
            // 把有效的attachment_id 变成 use_status= F 变成 enable=F
            $new_image = array_merge($input['diagnosis_report'], $input['appraisal_report']);
        }

        DB::beginTransaction();
        try {
            $del_image_ids = array_diff($old_image, $new_image);
            $add_image_ids = array_diff($new_image, $old_image);
            if ($del_image_ids > 0) {
                $this->updateAttachmentAfterNotUseAgain($del_image_ids);
            }
            if ($add_image_ids > 0) {
                $this->saveAttachmentAfterSave($add_image_ids);
            }

            $input['diagnosis_report'] = implode(',', $input['diagnosis_report']);
            $input['appraisal_report'] = implode(',', $input['appraisal_report']);
            $input["updated_at"] = Carbon::now()->toDateTimeString();
            $this->fill($input)->save();
            DB::commit();
            return $this->baseSucceed([], '操作成功');
        } catch (\Exception $e) {
            throw $e;
            DB::rollBack();
            return $this->baseFailed('内部错误');
        }
    }

    public function updateStatusAction($input)
    {
        DB::beginTransaction();
        try {
            $this->fill($input)->save();
            DB::commit();
            return $this->baseSucceed([], '操作成功');
        } catch (\Exception $e) {
            throw $e;
            DB::rollBack();
            return $this->baseFailed('内部错误');
        }
    }

    public function destroyAction()
    {
        DB::beginTransaction();
        try {
            $this->delete();
            DB::commit();
            return $this->baseSucceed([], '删除成功');
        } catch (\Exception $e) {
            throw $e;
            DB::rollBack();
            return $this->baseFailed('内部错误');
        }
    }
}
